<?php namespace Admin\Controller;
use Think\log;
use Think\Controller;
use MongoDB\Driver\Server;
use Admin\Model\AuthRuleModel;
use Admin\Model\AuthGroupModel;
use User\Api\UserApi as UserApi;
use Common\Model\PmWorkFlowModel;
use Admin\Common\POMBizClient;
use Admin\Common\POMVIPClient as VIP;
use Admin\Common\POMNetTools as T;

// TODO: PHP GateWay封装
class ApiController extends Controller
{
    public function test()
    {
      $ret = array();

      // $ret = $this->m_VIPHand->PushOrder(100,23);
      // $ret = $this->m_VIPHand->PlaceAdvanceOrder('sb',1,'[{"GoodsSn":"02568-pcs","price":1.10,"Quantity":100,"Validity":"1481697343"}]');
      $ret = $this->m_VIPHand->Purchase('[{"GoodsSn":"02568-pcs","Quantity":1}]',1);

      var_dump($ret);
    }
    public function sign()
    {
      $params = array();
      //参数

      //测试下单
      // $params["source_order_sn"] = "abcdefg1";
      // $params["is_test_order"]   = "true";
      // $params["goods_jsonstr"]  = '[{"goods_sn":"Swi011","quantity":2}]';

      // 正式下单
      $params["source_order_sn"] = "87sjibbbbbbb1111221";
      $params["idcardsys_key"]  = "sfdfeffsdffff32ffffff";
      $params["idcardno"]      = "4634524565242145";
      $params["remark"]        = "不要加";
      $params["goods_jsonstr"]  = '[{"goods_sn":"health004","quantity":1}]';
      $params["consignee"] = "彭双启";
      $params["address"]   = "高新园长虹科技大厦911";
      $params["province"]  = "广东";
      $params["city"]      = "深圳";
      $params["district"]  = "南山区";
      $params["mobile"]    = "13316838948";
      $params["email"]     = "dysf1462601@sina.cn";


      // $params["goods_sn"] = "NZBEES001";
      // $params["bar_code"] = "9311770598422";
      // $params["order_sn"] = "SN201612280037";
      // $params["source_order_sn"] = "1315011";

      //----------------------------------------------------
      $APPkeY = "abe6a618aafc0c89";
      $ret    = $this->m_VIPHand->getAppSecretForKey($APPkeY);
      $_url   = T::BuildUrlForSign($APPkeY,$params);
      $_sign  = T::BuildSign($ret,$params);
      echo $_sign;
      echo "<br>";
      echo $_url."&sign=".$_sign;
    }

    //TODO: 根据商品货号查询Bean给你的报价
    public function QueryGoodsPrice()
    {
      // 获取参数
      // 公共
      $APPkeY  = T::I("app_key","");
      $sign    = T::I("sign","");
      // 特有
      $GoodsSn = T::I("goods_sn","");
      $BarCode = T::I("bar_code","");

      // 验证参数缺省
      if( empty($GoodsSn) && empty($BarCode) )
      {
        $this->m_RetData["status"] = -167;
        $this->m_RetData["info"]   = "goods_sn与bar_code必须传一个。如果两 个都传取Barcode";
        $this->POMReturn();
      }

      // 验证参数合法
      $params = array();
      if( !empty($GoodsSn) )$params["goods_sn"] = $GoodsSn;
      if( !empty($BarCode) )$params["bar_code"] = $BarCode;
      $this->AuthParms($APPkeY ,$sign , $params );

      // TODO: 获取返回结果
      $price = $this->m_VIPHand->GetPriceForGoodsSnOrBarcode($GoodsSn,$BarCode) ;
      if( 0 > $price )
      {
        $this->m_RetData["status"] = -1;
        $this->m_RetData["info"]   = "货号在Bean查不到";
        $this->POMReturn();
      }
      $objtmp = json_decode($price,true);
      $this->m_RetData["data"]["price"]   = $objtmp["Price"];
      $this->m_RetData["data"]["taxrate"] = $objtmp["Taxrate"];
      $this->POMReturn();
    }

    //TODO: 根据商品货号查看你的云虚拟仓 库存
    public function QueryInventory()
    {
      // 获取参数
      // 公共
      $APPkeY  = T::I("app_key","");
      $sign    = T::I("sign","");
      // 特有
      $GoodsSn = T::I("goods_sn","");
      $BarCode = T::I("bar_code","");

      // 验证参数缺省
      if( empty($GoodsSn) && empty($BarCode) )
      {
        $this->m_RetData["status"] = -167;
        $this->m_RetData["info"]   = "goods_sn与bar_code必须传一个。如果两 个都传取bar_code";
        $this->POMReturn();
      }

      // 验证参数合法
      $params = array();
      if( !empty($GoodsSn) )$params["goods_sn"] = $GoodsSn;
      if( !empty($BarCode) )$params["bar_code"] = $BarCode;
      $this->AuthParms($APPkeY ,$sign , $params );

      // TODO: 获取返回结果
      $ret = $this->m_VIPHand->GetStockForGoodsSnOrBarcode($GoodsSn,$BarCode) ;
      if( false === $ret )
      {
        $this->m_RetData["status"] = -1;
        $this->m_RetData["info"]   = "货号在Bean查不到";
        $this->POMReturn();
      }
      $this->m_RetData["data"]["pri"]["quantity"]   = (int)$ret["PRI"]["Quantity"];
      $this->m_RetData["data"]["pri"]["salenumber"] = (int)$ret["PRI"]["Salenumber"];
      $this->m_RetData["data"]["pub"]["quantity"]   = (int)$ret["PUB"]["Quantity"];
      $this->m_RetData["data"]["pub"]["salenumber"] = (int)$ret["PUB"]["Salenumber"];
      $this->POMReturn();
    }


    //TODO: 根据订单号查询其状态和对应的发货单状态
    public function QueryDelivery()
    {
      // 获取参数
      // 公共
      $APPkeY  = T::I("app_key","");
      $sign    = T::I("sign","");
      // 特有
      $OrderSn       = T::I("order_sn","");
      $SourceOrderSn = T::I("source_order_sn","");

      // 验证参数缺省
      if( empty($OrderSn) && empty($SourceOrderSn) )
      {
        $this->m_RetData["status"] = -167;
        $this->m_RetData["info"]   = "order_sn 与 source_order_sn 必须传一个。如果两 个都传取 order_sn";
        $this->POMReturn();
      }

      // 验证参数合法
      $params = array();
      if( !empty($OrderSn) )      $params["order_sn"]       = $OrderSn;
      if( !empty($SourceOrderSn) )$params["source_order_sn"] = $SourceOrderSn;
      $this->AuthParms($APPkeY ,$sign , $params );

      // TODO: 获取返回结果
      $ret = $this->m_VIPHand->GetDeliveryInfoForOrderSNAndSoucesysOrderSn($OrderSn,$SourceOrderSn) ;
      if( false === $ret )
      {
        $this->m_RetData["status"] = -1;
        $this->m_RetData["info"]   = "订单在Bean查不到";
        $this->POMReturn();
      }

      $DeliveryStatus = json_decode( $ret["DeliveryStatusJson"],true);

      $this->m_RetData["data"]["order_status"] = $ret["OrderStatus"];

      for( $i = 0 ; $i < count($DeliveryStatus) ; $i++ )
      {
        $this->m_RetData["data"]["delivery_status"][$i]["delivery_sn"]         = $DeliveryStatus[$i]["DeliverySn"];
        $this->m_RetData["data"]["delivery_status"][$i]["invoiceno"]           = $DeliveryStatus[$i]["InvoiceNo"];
        $this->m_RetData["data"]["delivery_status"][$i]["expresscompany_name"] = $DeliveryStatus[$i]["ExpresscompanyName"];
        $this->m_RetData["data"]["delivery_status"][$i]["express_url"]         = $DeliveryStatus[$i]["ExpressUrl"];
        $this->m_RetData["data"]["delivery_status"][$i]["consignee"]           = $DeliveryStatus[$i]["Consignee"];
        $this->m_RetData["data"]["delivery_status"][$i]["address"]             = $DeliveryStatus[$i]["Address"];
        $this->m_RetData["data"]["delivery_status"][$i]["status"]              = $DeliveryStatus[$i]["Status"];
      }

      $this->POMReturn();
    }


    //TODO: 同步订单到云供应链系统
    public function PlaceOrder()
    {
      // 获取参数
      // 公共
      $APPkeY  = T::I("app_key","");
      $sign    = T::I("sign","");
      // 特有
      $SourceOrderSn = T::I("source_order_sn","");
      $GoodsJsonStr  = T::I("goods_jsonstr","");
      $Consignee     = T::I("consignee","");
      $Address       = T::I("address","");
      $Zipcode       = T::I("zipcode","");
      $Tel           = T::I("tel","");
      $Mobile        = T::I("mobile","");
      $Email         = T::I("email","");
      $Country       = T::I("country","");
      $Province      = T::I("province","");
      $City          = T::I("city","");
      $District      = T::I("district","");
      $SignBuilding  = T::I("sign_building","");
      $IdcardSysKey  = T::I("idcardsys_key","");
      $IdcardNo      = T::I("idcardno","");
      $Remark        = T::I("remark","");
      $IsTestOrder   = T::I("is_test_order",false);

      // 验证参数合法
      $params = array();
      $arrtmp = array();
      $params["SourceOrderSn"] = $SourceOrderSn;
      $arrtmp["source_order_sn"] = $SourceOrderSn;
     // 合并商品相同的数量
      $goodsArr = array();
      $goodsArr2= json_decode($GoodsJsonStr,true);

      for( $i = 0 ; $i< count($goodsArr2) ; $i++ )
      {
        $goodsArr[$i]["GoodsSn"]  = $goodsArr2[$i]["goods_sn"];
        $goodsArr[$i]["Quantity"] = $goodsArr2[$i]["quantity"];
      }

      $GoodsJsonArr = T::merge_quantity($goodsArr) ;
      $params["GoodsJsonStr"]   = json_encode($GoodsJsonArr) ;
      $arrtmp["goods_jsonstr"]  = json_encode($goodsArr2) ;
      if( strtoupper( $IsTestOrder) != "TRUE" )
      {
        $params["Remark"]    = $Remark;
        $arrtmp["remark"]    = $Remark;
        $params["Consignee"] = $Consignee;
        $arrtmp["consignee"] = $Consignee;
        $params["Address"]   = $Address;
        $arrtmp["address"]   = $Address;
        $params["Province"]  = $Province;
        $arrtmp["province"]  = $Province;
        $params["City"]      = $City;
        $arrtmp["city"]      = $City;
        $params["District"]  = $District;
        $arrtmp["district"]  = $District;
        $params["Mobile"]    = $Mobile;
        $arrtmp["mobile"]    = $Mobile;
      }
      $this->AuthNeedParms( $arrtmp );

      if( !empty($Remark) )      { $arrtmp["remark"]       = $Remark;       $params["Remark"]       = $Remark;}
      if( !empty($Consignee) )   { $arrtmp["consignee"]    = $Consignee;    $params["Consignee"]    = $Consignee;}
      if( !empty($Zipcode) )     { $arrtmp["zipcode"]      = $Zipcode;      $params["Zipcode"]      = $Zipcode;}
      if( !empty($Address) )     { $arrtmp["address"]      = $Address;      $params["Address"]      = $Address;}
      if( !empty($Province) )    { $arrtmp["province"]     = $Province;     $params["Province"]     = $Province;}
      if( !empty($City) )        { $arrtmp["city"]         = $City;         $params["City"]         = $City;}
      if( !empty($District) )    { $arrtmp["district"]     = $District;     $params["District"]     = $District;}
      if( !empty($Mobile) )      { $arrtmp["mobile"]       = $Mobile;       $params["Mobile"]       = $Mobile;}
      if( !empty($Tel) )         { $arrtmp["tel"]          = $Tel;          $params["Tel"]          = $Tel;}
      if( !empty($Email) )       { $arrtmp["email"]        = $Email;        $params["Email"]        = $Email;}
      if( !empty($Country) )     { $arrtmp["country"]      = $Country;      $params["Country"]      = $Country;}
      if( !empty($SignBuilding)) { $arrtmp["sign_building"]= $SignBuilding; $params["SignBuilding"] = $SignBuilding;}
      if( !empty($IdcardSysKey)) { $arrtmp["idcardsys_key"]= $IdcardSysKey; $params["IdcardSysKey"] = $IdcardSysKey;}
      if( !empty($IdcardNo) )    { $arrtmp["idcardno"]     = $IdcardNo;     $params["IdcardNo"]     = $IdcardNo;}
      if( !empty($IsTestOrder) ) { $arrtmp["is_test_order"]= $IsTestOrder;  $params["IsTestOrder"]  = $IsTestOrder;}
      $this->AuthParms($APPkeY ,$sign , $arrtmp );

      //-------
      $ret = null;
      if( strtoupper( $IsTestOrder) == "TRUE" )
        $ret = $this->m_VIPHand->SimulatePlaceOrder($params);
      else
        $ret = $this->m_VIPHand->RegularPlaceOrder($params);

      if( false === $ret )
      {
        $this->m_RetData["status"] = -165;
        $this->m_RetData["info"]   = "网络错误";
        $this->POMReturn();
      }
      if( 0 != $ret["RetCode"] )
      {
        $this->m_RetData["status"] = -1;
        $this->m_RetData["info"]   = $ret["Message"];
        $this->POMReturn();
      }

      $this->m_RetData["data"]["order_id"] = $ret["OrderId"];
      $this->m_RetData["data"]["order_sn"] = $ret["OrderSn"];
      $this->POMReturn();
    }


    //TODO: 下单API的补充，考虑到身份证信息收集不及时的情况
    public function PlaceIdCard()
    {
      // 获取参数
      // 公共
      $APPkeY  = T::I("app_key","");
      $sign    = T::I("sign","");
      // 特有
      $SourceOrderSn = T::I("source_order_sn","");
      $IdcardSysKey  = T::I("idcardsys_key","");
      $IdcardNo      = T::I("idcardno","");

      // 验证参数合法
      $params = array();
      $params["source_order_sn"] = $SourceOrderSn;
      $params["idcardsys_key"]   = $IdcardSysKey;
      $params["idcardno"]        = $IdcardNo;
      $this->AuthNeedParms( $params );
      $this->AuthParms($APPkeY ,$sign , $params );

      // TODO: 获取返回结果
      $ret = $this->m_VIPHand->SetIdCardMsg($SourceOrderSn,$IdcardSysKey,$IdcardNo) ;
      if( false === $ret )
      {
        $this->m_RetData["status"] = -1;
        $this->m_RetData["info"]   = "错误的订单ID";
        $this->POMReturn();
      }
      $this->POMReturn();
    }


    //TODO: 通用数据返回格式
    private $m_RetData = array();
    private $m_VIPHand = null;
    private function POMReturn()
    {
      // echo json_encode($this->m_RetData);
      $this->ajaxReturn( ( $this->m_RetData ) ,'JSON');
      exit;
    }
    protected function _initialize()
    {
      $this->m_RetData["status"] = 0;
      $this->m_RetData["info"]   = "";
      $this->m_RetData["data"]   = array();

      $this->m_VIPHand = new VIP();
    }
    // 验证参数必须
    protected function AuthNeedParms($params = array())
    {
      foreach ($params as $key => $value)
      {
        if( empty( $value ) )
        {
          $this->m_RetData["status"] = -166;
          $this->m_RetData["info"]   = $key." 不能为空";
          $this->POMReturn();
        }
      }
    }
    // 参数验证函数
    protected function AuthParms($APPkeY, $sign , $params = array() )
    {
      $APPSecret = $this->m_VIPHand->getAppSecretForKey($APPkeY);
      $_sign     = T::BuildSign($APPSecret , $params);
      if( $sign != $_sign )
      {
        $this->m_RetData["status"] = -168;
        $this->m_RetData["info"]   = "参数不合法";
        $this->POMReturn();
      }
    }
}
